<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <!-- 引入样式 -->
    <link href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="stylesheet">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="../app/lib/ZohoCrmHelper.js" type="text/javascript"></script>
    <script src="../app/lib/ZSDK.js" type="text/javascript"></script>
    <script src="../app/lib/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="../app/lib/ZohoEmbededAppSDK.min.js" type="text/javascript"></script>
    <script src="../app/lib/axios.min.js" type="text/javascript"></script>
    <title>CheckOut</title>
    <style>
        .form-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .form-wrapper {
            width: 80%;
            max-width: 800px;
        }

        .button-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .title {
            text-align: center;
            margin: 20px 0;
        }

        .upload-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
    </style>
</head>

<body>
<div id="app">
    <h1 class="title">CheckOut</h1>
    <div class="form-container">
        <div class="form-wrapper">
            <el-form label-position="left" label-width="auto">
                <el-form-item label="remark">
                    <el-input type="textarea" v-model="remark" placeholder="remark"></el-input>
                </el-form-item>
                <el-form-item label="fileList">
                    <div class="upload-container">
                        <el-upload
                                class="upload-demo"
                                ref="upload"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :on-remove="handleRemove"
                                :on-change="handleFileChange"
                                :limit="3"
                                :file-list="fileList"
                                :auto-upload="false">
                            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                            <el-button style="margin-left: 10px;" size="small" type="success" @click="saveFile()">上传到服务器
                            </el-button>
                            <div slot="tip" class="el-upload__tip">只能上传10个文件，且不超过20MB</div>
                        </el-upload>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div class="button-container">
        <el-button type="primary" @click="onSubmit">submit</el-button>
    </div>
</div>
<script type="text/javascript">
    const app = new Vue({
        el: '#app',
        data() {
            return {
                crmId: 0,
                remark: '', // 备注
                fileList: [] // 附件（存储上传后的文件信息）
            };
        },
        mounted() {
            this.initData();
            ZOHO.embeddedApp.init();
        },
        methods: {
            initData() {
                ZOHO.embeddedApp.on("PageLoad", function (data) {
                    app.crmId = data.EntityId;
                });
            },
            // 表单提交
            async onSubmit() {
                let config = {
                    Entity: "Events",
                    APIData: {
                        "id": app.crmId + "",
                        "Content": app.remark
                    }
                }
                ZOHO.CRM.API.updateRecord(config).then(function (data) {
                    console.log(data);
                    if (data.data[0].code === "SUCCESS") {
                        app.$message({
                            type: 'success',
                            message: 'CheckOut success!'
                        });
                    } else {
                        app.$message({
                            message: data.data[0].message,
                            type: 'error'
                        });
                    }
                })
                await this.sleep(1000);
                ZOHO.CRM.UI.Popup.closeReload()
                    .then(function (data) {
                        console.log(data)
                    });
            },
            sleep(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            },

            //保存图片
            async saveFile() {
                // console.log('当前选择的文件数量:', this.fileList.length);
                // console.log('当前选择的文件:', this.fileList);
                if (this.fileList.length > 0) {

                    const loading = this.$loading({
                        lock: true,
                        text: '上传中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    try {
                        for (let i = 0; i < this.fileList.length; i++) {
                            const file = this.fileList[i].raw; // 获取原始文件对象
                            const filename = this.fileList[i].name;
                            // 直接使用 File 对象上传
                            await ZOHO.CRM.API.attachFile({
                                Entity: "Events",
                                RecordID: this.crmId,
                                File: {Name: filename, Content: file} // 直接传递 File 对象
                            });
                        }
                        loading.close();
                        this.$message.success('所有文件上传成功');
                    } catch (error) {
                        loading.close();
                        console.error('上传失败:', error);
                        this.$message.error('上传失败');
                    }
                }
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handleFileChange(file, fileList) {
                const isLt20M = file.size / 1024 / 1024 < 20;
                const isWithinLimit = fileList.length < 10;

                if (!isLt20M) {
                    this.$message.error('上传文件大小不能超过20MB!');
                    return;
                }

                if (!isWithinLimit) {
                    this.$message.error('只能上传10个文件!');
                    return;
                }

                this.fileList = fileList;
            }
        }
    });
</script>
</body>

</html>
